
import numpy as np
import struct


 
#载入数据集
def load_data():
    with open('E:\\文件\\vision\\mnist_dataset\\t10k-images.idx3-ubyte','rb') as x:
        magic,num,rows,cols = struct.unpack('>IIII',x.read(16))
        images = np.fromfile(x,dtype = np.uint8)
    with open('E:\\文件\\vision\\mnist_dataset\\t10k-labels.idx1-ubyte','rb') as y:
        magic,n = struct.unpack('>II',y.read(8))
        labels  = np.fromfile(y,dtype = np.uint8)
    return images,labels
t_images,t_labels = load_data()
print(t_images.shape)
print('')
x = t_images.reshape(-1,28*28)   #(10000,784)

print(x.shape)
print(t_labels.shape)



#初始化权重和偏置
def init_network():                                          
    network = {}
    weight_scale = 1e-3
    network['w1'] = np.random.randn(784,50) * weight_scale
    network['b1'] = np.ones(50)
    network['w2'] = np.random.randn(50,100) * weight_scale
    network['b2'] = np.ones(100)
    network['w3'] = np.random.randn(100,10) * weight_scale
    network['b3'] = np.ones(10)
    return network


def relu(x):
    return np.maximum(0,x)
def softmax(x):
    if x.ndim == 2:
        c = np.max(x,axis = 1)
        x = x.T -c #溢出对策
        y = np.exp(x) / np.sum(np.exp(x),axis = 0)
        return y.T
    c = np.max(x)
    exp_x = np.exp(x-c)
    return exp_x / np.sum(exp_x)
def mean_squared_error_(x,t_labels):
    return np.sum( (x-t_labels)**2 )/len(x)
    

def forward(network,x):
    w1,w2,w3 = network['w1'],network['w2'],network['w3']
    b1,b2,b3 = network['b1'],network['b2'],network['b3']  
    a1 = x.dot(w1) + b1
    z1 = relu(a1)
    
    a2 = z1.dot(w2) + b2
    z2 = relu(a2)
    
    a3 = z2.dot(w3) + b3
    z3 = relu(a3)
    y = z3
    return y
network = init_network()
accuracy_cnt = 0
batch_size = 5
ite_ = []
for i in range(0,20,batch_size):
    x_batch = x[i:i + batch_size]
    y_batch = forward(network,x_batch)   #输出100*10的矩阵，100行表示100张图片,10表示每张图的10个类别
    p = softmax(y_batch)
    print(p)
    p = np.argmax(p,axis = 1)     #p是100*1的矩阵，100表示100张图片，1表示对应图片的最大输出
    print(p)
    
   # mean_squared_errors = mean_squared_error_(p,t_labels[i:i + batch_size])
    #ite_.append(mean_squared_errors)
    
    accuracy_cnt = np.sum(p == t_labels[i:i + batch_size])
print('每次的均方差：',ite_)
print('accuracy:' + str(float(accuracy_cnt) / len(x) * 100) + '%')
